package com.rcloud.stock.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.ListAdapter;
import androidx.recyclerview.widget.RecyclerView;

import com.rcloud.stock.R;
import com.rcloud.stock.database.History;
import com.rcloud.stock.ui.search.SearchViewModel;

public class SearchHistoryAdapter extends ListAdapter<History, SearchHistoryAdapter.ViewHolder> {
    private final SearchViewModel model;
    public SearchHistoryAdapter(SearchViewModel model) {
        super(new DiffUtil.ItemCallback<History>() {
            @Override
            public boolean areItemsTheSame(@NonNull History oldItem, @NonNull History newItem) {
                return oldItem.getId()==newItem.getId();
            }

            @Override
            public boolean areContentsTheSame(@NonNull History oldItem, @NonNull History newItem) {
                return oldItem.getContent().equals(newItem.getContent());
            }
        });
        this.model = model;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cell_search_history,parent,false);
        ViewHolder holder = new ViewHolder(view);
        holder.itemView.setOnClickListener(v -> {
            //填充edittext
            History history = (History) v.getTag(R.integer.history_tag);
            model.getPatternLive().setValue(history.getContent());
        });
        holder.deleteHistoryBtn.setOnClickListener(v -> {
            //删除当前选中项
            model.deleteHistory((History) v.getTag(R.integer.history_tag));
        });
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        holder.searchHistoryText.setText(getItem(position).getContent());
        holder.deleteHistoryBtn.setTag(R.integer.history_tag,getItem(position));
        holder.itemView.setTag(R.integer.history_tag,getItem(position));
    }

    public static class ViewHolder extends RecyclerView.ViewHolder{
        private final TextView searchHistoryText;
        private final ImageView deleteHistoryBtn;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            searchHistoryText = itemView.findViewById(R.id.search_history_tv);
            deleteHistoryBtn = itemView.findViewById(R.id.deleteHistoryBtn);
        }
    }
}
